package com.hry.sunflower.images.controller;

import com.hry.sunflower.images.common.response.Result;
import com.hry.sunflower.images.config.ImageProperties;
import com.hry.sunflower.images.exception.BusinessException;
import com.hry.sunflower.images.service.ImageService;
import com.hry.sunflower.images.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;

/**
 * @Desc
 * @Author houry
 * @Date 2021/1/23 16:22
 **/
@RestController
@Slf4j
public class ImageController {

    @Autowired
    private ImageService imageService;

    /**
     * 上传文件
     *
     * @return 上传结果
     */
    @PostMapping("dealWithImage")
    public void dealImage(@RequestParam("file") MultipartFile files, @RequestParam("size") double size, HttpServletResponse  response) {
        try {
            log.info("[ImageController]-[uploadImage]-[file = {}]", files.getOriginalFilename());
            String downloadPath = imageService.dealImage(files, size);
            File file = new File(downloadPath);
            FileImageInputStream fs = new FileImageInputStream (file);
            int streamLength = (int)fs.length();
            byte[] image = new byte[streamLength];
            fs.read(image,0,streamLength);
            fs.close();
            response.setHeader("Content-Type","application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename="+"monkey.png");
            response.getOutputStream().write(image);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (BusinessException e) {
            log.error("[ImageController]-[uploadImage]-[BusinessException]", e);
        } catch (Exception e) {
            log.error("[ImageController]-[uploadImage]-[Exception]", e);

        }
    }


}
